﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TheOutfield.UmbExt.PrivateMessaging.Model;

namespace TheOutfield.UmbExt.PrivateMessaging.Data
{
    public class PrivateMessageRepository
    {
        protected Connection conn;

        public PrivateMessageRepository()
        {
            conn = new Connection();
        }

        public PrivateMessage GetPrivateMessage(int memberId, int messageId)
        {
            PrivateMessage message = null;

            using (var dc = conn.GetContext())
            {
                message = (
                    from r in dc.Recipients
                    join m in dc.Messages on r.MessageId equals m.MessageId
                    where r.MemberId == memberId && r.MessageId == messageId
                    select new PrivateMessage()
                    {
                        Message = m,
                        Recipient = r
                    }
                ).First();
            }

            return message;
        }

        public List<PrivateMessage> GetPrivateMessages(int memberId, MessageFolder folder)
        {
            List<PrivateMessage> result = new List<PrivateMessage>();

            using (var dc = conn.GetContext())
            {
                IEnumerable<PrivateMessage> messages = (
                    from r in dc.Recipients
                    join m in dc.Messages on r.MessageId equals m.MessageId
                    where r.MemberId == memberId && r.Folder == folder
                    orderby m.CreateDate descending
                    select new PrivateMessage()
                    {
                        Message = m,
                        Recipient = r
                    });

                result = messages.ToList();
            }

            return result;
        }

        public void DeletePrivateMessage(int memberId, int messageId)
        {
            using (var dc = conn.GetContext())
            {
                dc.Recipients.DeleteOnSubmit(dc.Recipients.Where(r => r.MemberId == memberId && r.MessageId == messageId).FirstOrDefault());
                dc.SubmitChanges();

                //if the last recipient was deleted
                //...also delete the message
                int remainingRecipientCount = dc.Recipients.Where(r => r.MessageId == messageId).Count();
                if (remainingRecipientCount == 0)
                {
                    dc.Messages.DeleteOnSubmit(dc.Messages.Where(m => m.MessageId == messageId).FirstOrDefault());
                    dc.SubmitChanges();
                }
            }
        }
    }
}